<template>
    <div class="container">
        <h1 class="my-4">用户列表</h1>
        <table class="table table-striped">
            <thead>
                <tr>
                    <th scope="col">ID</th>
                    <th scope="col">用户名</th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="user in currentPageUsers" :key="user.id">
                    <td>{{ user.id }}</td>
                    <td>{{ user.username }}</td>
                </tr>
            </tbody>
        </table>
        <nav aria-label="用户分页导航">
            <ul class="pagination justify-content-center">
                <li class="page-item" :class="{ disabled: currentPage === 1 }">
                    <a class="page-link" href="#" @click.prevent="prevPage">上一页</a>
                </li>
                <li v-for="page in totalPages" :key="page" class="page-item" :class="{ active: page === currentPage }">
                    <a class="page-link" href="#" @click.prevent="goToPage(page)">{{ page }}</a>
                </li>
                <li class="page-item" :class="{ disabled: currentPage === totalPages }">
                    <a class="page-link" href="#" @click.prevent="nextPage">下一页</a>
                </li>
            </ul>
        </nav>
    </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';

// 生成 15 条模拟用户数据
const users = ref([
    { id: 1, username: 'user01' },
    { id: 2, username: 'user02' },
    { id: 3, username: 'user03' },
    { id: 4, username: 'user04' },
    { id: 5, username: 'user05' },
    { id: 6, username: 'user06' },
    { id: 7, username: 'user07' },
    { id: 8, username: 'user08' },
    { id: 9, username: 'user09' },
    { id: 10, username: 'user10' },
    { id: 11, username: 'user11' },
    { id: 12, username: 'user12' },
    { id: 13, username: 'user13' },
    { id: 14, username: 'user14' },
    { id: 15, username: 'user15' }
]);

// 每页显示的项目数量
const itemsPerPage = ref(5);
// 当前页码
const currentPage = ref(1);

// 计算总页数
const totalPages = computed(() => Math.ceil(users.value.length / itemsPerPage.value));

// 计算当前页的用户数据
const currentPageUsers = computed(() => {
    const startIndex = (currentPage.value - 1) * itemsPerPage.value;
    const endIndex = startIndex + itemsPerPage.value;
    return users.value.slice(startIndex, endIndex);
});

// 上一页
const prevPage = () => {
    if (currentPage.value > 1) {
        currentPage.value--;
    }
};

// 下一页
const nextPage = () => {
    if (currentPage.value < totalPages.value) {
        currentPage.value++;
    }
};

// 跳转到指定页码
const goToPage = (page: number) => {
    currentPage.value = page;
};
</script>

<style scoped>
/* 可以在这里添加自定义样式 */
</style>